<?php

namespace App\Http\Controllers\web;

use App\Events\PostViewed;
use App\Helpers\Image;
use App\Http\Controllers\Controller;
use App\Http\Serve\IdCreate;
use App\Models\InWarehouse;
use App\Models\StoreProduct;
use App\Models\ToWarehouse;
use App\Models\Warehouse;
use App\Repos\PostRepo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use think\Exception;

class WarehouseController extends Controller
{

    /**
     * 仓库管理
     * @return Warehouse[]|array|\Illuminate\Database\Eloquent\Collection
     */
    public function warehouseList(){
        try {
            $data=Warehouse::all();
            if ($data){
                return   ['code'=>20000,'msg'=>'查询成功','data'=>$data];
            }
            throw new \Exception('查询失败');
        }catch (\Exception $e){
            return  ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }

    /**
     * 仓库添加
     * @param Request $request
     * @return array
     */
    public function CreateWarehouse(Request $request){
        try {
            $validatedData = $request->validate([
                'warehouse_name' => 'required',
                'warehouse_address' => 'required',
                'warehouse_coordinate' => 'required',
                'warehouse_num' => 'required',
                'warehouse_status' => 'required',
            ]);
            $arr=[
                'warehouse_name'=>$validatedData['warehouse_name'],
                'warehouse_address'=>$validatedData['warehouse_address'],
                'warehouse_coordinate'=>$validatedData['warehouse_coordinate'],
                'warehouse_num'=>$validatedData['warehouse_num'],
                'warehouse_status'=>$validatedData['warehouse_status'],
            ];
            $data=Warehouse::create($arr);
            if ($data){
                return   ['code'=>20000,'msg'=>'添加成功'];
            }
            throw new \Exception('添加失败');
        }catch (\Exception $e){
            return  ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }

    /**
     * 仓库修改
     * @param Request $request
     * @return array
     */
    public function warehouseUpdate(Request $request){
        try {
            $validatedData = $request->validate([
                'id' => 'required',
                'warehouse_name' => 'required',
                'warehouse_address' => 'required',
                'warehouse_coordinate' => 'required',
                'warehouse_num' => 'required',
                'warehouse_status' => 'required',
            ]);
            $arr=[
                'warehouse_name'=>$validatedData['warehouse_name'],
                'warehouse_address'=>$validatedData['warehouse_address'],
                'warehouse_coordinate'=>$validatedData['warehouse_coordinate'],
                'warehouse_num'=>$validatedData['warehouse_num'],
                'warehouse_status'=>$validatedData['warehouse_status'],
            ];
            $data=Warehouse::where('id',$validatedData['id'])->update($arr);
            if ($data){
                return   ['code'=>20000,'msg'=>'修改成功'];
            }
            throw new \Exception('添加失败');
        }catch (\Exception $e){
            return  ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }

    /**
     * 查询仓库商品
     * @param Request $request
     * @return array
     */
    public function InWarehouse(Request $request){
        try {
            $max = $request->get('max');
            $min = $request->get('min');
            $warehouseName = $request->get('query');
            $where = [];
            if (!empty($warehouseName)) {
                $where[] = ['goods_names', 'like', "$warehouseName%"];
            }
            if (!empty($max) && !empty($min)) {
                $where[] = ['created_at', '>', "$max"];
                $where[] = ['created_at', '<', "$min"];
            }
            $data = Warehouse::leftjoin('inwarehouse', 'inwarehouse.wid', '=', 'warehouse.id')->where($where)->get();

            if ($data) {
                return ['code' => 20000, 'msg' => '查询成功', 'data' => $data];
            }
            throw new \Exception('查询失败');
        }catch (\Exception $e){
            return  ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }
    /**
     * 添加商品入库
     * @param Request $request
     * @return array
     */
    public function createInWarehouse(Request $request){
        try {
            $data = $request->post();
            IdCreate::machineId($data['wid']);
            $order_id = IdCreate::createOnlyId();
            $datas = Warehouse::where('id', $data['wid'])->first();
            $arr = [
                'wid' => $data['wid'],
                'goods_img' => $data['goods_img'],
                'goods_names' => $data['goods_names'],
                'goods_specification' => $data['goods_specification'],
                'goods_serial' => $datas['id'].'_'.$order_id,
                'warehouse_name' => $datas['warehouse_name'],
                'goods_num' => $data['goods_num'],
            ];
            $data = InWarehouse::create($arr);
            if ($data) {
                return ['code' => 20000, 'msg' => '添加成功'];
            }
            throw new \Exception('添加失败');
        }catch (\Exception $e){
            return  ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }
    /**
     * 修改库中的商品
     * @param Request $request
     * @return array
     */
    public function updateInWarehouse(Request $request){
        try {
            $data=$request->post();
            $arr=[
                'id'=>$data['id'],
                'wid'=>$data['wid'],
                'goods_img'=>$data['goods_img'],
                'goods_names'=>$data['goods_names'],
                'goods_specification'=>$data['goods_specification'],
                'goods_num'=>$data['goods_num'],
            ];
            $data=InWarehouse::where('wid',$data['wid'])->where('id',$data['id'])->update($arr);
            if ($data){
                return   ['code'=>20000,'msg'=>'修改成功'];
            }
            throw new \Exception('修改失败');
        }catch (\Exception $e){
            return  ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }
    /**
     * 入库商品删除
     * @param Request $request
     * @return array
     */
    public function deleteInWarehouse(Request $request){
        try {
            $id=$request->get('id');
            $del=InWarehouse::where('id',$id)->delete();
            if ($del){
                return   ['code'=>20000,'msg'=>'删除成功'];
            }
            throw new \Exception('删除失败');
        }catch (\Exception $e){
            return  ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }

    /**
     * 出库商品查询
     * @param Request $request
     * @return array
     */
    public function ToWarehouse(Request $request){
        try {
            $max = $request->get('max');
            $min = $request->get('min');
            $wid = $request->get('wid');
            $warehouseName = $request->get('querys');
            $limit = $request->get('limit');
            $where = [];
            if (!empty($warehouseName)) {
                $where[] = ['goods_name', 'like', "$warehouseName%"];
            }
            if (!empty($wid)) {
                $where[] = ['wid', '=', "$wid"];
            }
            if (!empty($max) && !empty($min)) {
                $where[] = ['created_at', '>=', "$max"];
                $where[] = ['created_at', '<=', "$min"];
            }
            $data = Warehouse::leftjoin('towarehouse', 'towarehouse.wid', '=', 'warehouse.id')->where($where)->paginate($limit);
            if ($data) {
                return ['code' => 20000, 'msg' => '查询成功', 'data' => $data];
            }
            throw new \Exception('查询失败');
        }catch (\Exception $e){
            return  ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }

    /**
     * 出台商品添加
     * @param Request $request
     * @return array
     */
    public function createToWarehouse(Request $request){
        try {
            $id = $request->post('id');
            $wid = $request->post('wid');
            $num = $request->post('goods_num');
            $inGoods = InWarehouse::where('wid', $wid)->where('id', $id)->first();

            if ($inGoods['goods_num'] - $num < 0) {
                throw new \Exception('么有这么多库存');
            }
            $warehouse = Warehouse::where('id', $wid)->first();
            IdCreate::machineId($id);//编号
            $order_id = IdCreate::createOnlyId();
            $arr = [
                'wid' => $inGoods['wid'],
                'goods_img' => $inGoods['goods_img'],
                'goods_name' => $inGoods['goods_names'],
                'goods_specification' => $inGoods['goods_specification'],
                'goods_serial' => $warehouse['id'].$order_id,
                'warehouse_name' => $warehouse['warehouse_name'],
                'goods_num' => $num,
            ];
            $data = ToWarehouse::create($arr);
            if ($data) {
                $res = InWarehouse::where('id', $id)->update(['goods_num' => $inGoods['goods_num'] - $num]);

                if ($res) {
                    return ['code' => 20000, 'msg' => '出库成功'];
                }
                throw new \Exception('删除失败');
            }
            throw new \Exception('删除失败');
        }catch (\Exception $e){
            return  ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }

    /**
     * 出库商品修改
     * @param $request
     * @return array
     */
    public function updateToWarehouse(Request $request){
        try {
            $validatedData = $request->validate([
                'id' => 'required',
                'wid' => 'required',
                'goods_img' => 'required',
                'goods_name' => 'required',
                'goods_specification' => 'required',
                'goods_num' => 'required',
            ]);
            $arr=[
                'wid'=>$validatedData['wid'],
                'goods_img'=>$validatedData['goods_img'],
                'goods_name'=>$validatedData['goods_name'],
                'goods_specification'=>$validatedData['goods_specification'],
                'goods_num'=>$validatedData['goods_num'],
            ];
            $data=ToWarehouse::where('id',$validatedData['id'])->update($arr);
            if ($data){
                return   ['code'=>20000,'msg'=>'修改成功'];
            }
            throw new \Exception('修改失败');
        }catch (\Exception $e){
            return  ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }
    /**
     * 出库商品删除
     * @param Request $request
     * @return array
     */
    public function deleteToWarehouse(Request $request){
        try {
            $id=$request->get('id');
            $del=ToWarehouse::where('id',$id)->delete();
            if ($del){
                return   ['code'=>20000,'msg'=>'删除成功'];
            }
            throw new \Exception('删除失败');
        }catch (\Exception $e){
            return  ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }

    public function uploadImg(Request $request){
        $file=$request->file('file');
        try {
            $AK="_nYMEBn2a9PNaF4CjroG8yAiKwbkKwC7Fgh77ibL";
            $SK="VTDnwj7YMs8Gtejq9ed0a78wqFCNMU5peus3wNVH";
            $bucket="wangyesong";
            $url="http://image.licaidie.top/";
            $obj=new Image();
            $images=$obj->uploadFile($file,$AK,$SK,$bucket,$url);
            return ['code'=>20000,'msg'=>'上传成功','data'=>$images];
        }catch (\Exception $e){
            return ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }

    /**
     * 商品统计
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function goodsCount(){
        $data=StoreProduct::orderBy('price','desc')->get()->toarray();
         $arr=[];
        try {
            foreach ($data as $v){
               array_push($arr,['name'=>$v['store_name'],'price'=>$v['price']]);
            }
            return  $this->success('成功',$arr);
        }catch (\Exception $e){
            return ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }

    /**
     * 商品详情
     * @param Request $request
     * @return array|void
     */
    public function goodsRand(Request $request){
        $goodsId=$request->get('id');
        try {
            $data=StoreProduct::where('id',$goodsId)->first();
            return  ['code'=>20000,'msg'=>'成功','data'=>[$data]];
        }catch (\Exception $e){
            return ['code'=>5000,'msg'=>$e->getMessage()];
        }
    }




}

